define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');

    require('../../../c/pagination/index');

    require('./outflatGoods-list-tpl');
    require('./onfailnotice-list-tpl');
    require('./outflatMarks-list-tpl');

    var outFlatListTpl = juicer.templates['outflatGoods-list.juicer.html'];
    var onFailNoticeTpl = juicer.templates['onfailnotice-list.juicer.html'];
    var markListTpl = juicer.templates['outflatMarks-list.juicer.html'];

    var pageIndex = 1;
    var pageSize = 20;
    var FIRST_TIME_PAGI = true;

    var outflat = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "外店商品管理") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            //默认取urlParam参数
            var shopId = CRM.getUrlParam("id");
            if (shopId){
                //alert(shopId);
                $("#savedShopId").val(shopId);
                this.initSidebar(shopId);
                this.initShopInfo(shopId);
            }
            this.bindEvent();
        },
        /*
        侧边栏目录初始化
         */
        initSidebar: function (shopId) {
            var _url = CRM.getOuterUrl('/itemcenter/api/category/treeHasItem') + '/' + shopId;
            CRM.request({
                "type": 'GET',
                "url": _url,
                "dataType": "json",
                contentType: "application/json",
                "data": {
                    "itemStatus":100,
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    var html = "";
                    var listHtml = "";
                    var listChildHtml = "";
                    if (req.status) {
                        for (var i = 0;i < req.entry.length;i++){
                            if (req.entry[i].children.length > 0) {
                                for (var j = 0;j < req.entry[i].children.length;j++){
                                    listChildHtml += '<li data-value="' + req.entry[i].children[j].id + '"><a href="#">' + req.entry[i].children[j].name + '</a></li>';
                                }
                                listHtml += '<li data-value="' + req.entry[i].id + '"><a href="#">' + req.entry[i].name + '</a><ul>' + listChildHtml + '</ul>' + '</li>';
                                listChildHtml = "";
                            }else {
                                listHtml += '<li data-value="' + req.entry[i].id + '"><a href="#">' + req.entry[i].name + '</a></li>';
                            }
                            html += listHtml;
                            listHtml = "";
                        }
                        var _returnHtml = '<ul><li data-value=""><a href="#">全部商品</a><ul>' + html + '</ul></li></ul>';
                        $("#goodsMenu").html(_returnHtml);
                    }
                }
            })
        },
        /*
        全选
         */
        selectAll: function (isChecked) {
            if (isChecked){
                $(".onlySelect").prop("checked",true);
            }else {
                $(".onlySelect").prop("checked",false);
            }
        },
        /*
        营销活动下拉初始化
         */
        initOnAct: function (shopId) {
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/itemcenter/crm/item/activityInShop"),
                "dataType": "json",
                "data": {
                    "shopId" : shopId,
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    var html = "";
                    if (req.entry != null){
                        for (var i = 0;i < req.entry.length;i++){
                            html += '<option value="' + req.entry[i].id + '">' + req.entry[i].name + '</option>';
                        }
                    }
                    html = '<option value="">选择营销活动</option>' + html;
                    $("#onAct").html(html);
                }
            })
        },
        /*
        初始化商店信息
         */
        initShopInfo: function (shopId) {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/position"),
                "dataType": "json",
                contentType: "application/json",
                "data": {
                    "shopId" : shopId,
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    $("#shopInfo button").removeAttr('disabled');
                    if (req.status){
                        $("#shopInfo h3").html(req.entry.shopName);
                        $("#shopInfo h3").attr('data-city',req.entry.cityCode);
                        $("#goodsMenu li").removeClass('nowactive');
                        var currentPlat = [];
                        for (var i in req.entry.platforms){
                            currentPlat.push(req.entry.platforms[i].id);
                        }
                        //console.log(currentPlat);
                        $("#shopInfo button[data-id='" + currentPlat[0] +"']").addClass('active');
                        if (currentPlat.indexOf(10) < 0){
                            $("#shopInfo button[data-id='10']").attr('disabled','disabled');
                        }
                        if (currentPlat.indexOf(1) < 0){
                            $("#shopInfo button[data-id='1']").attr('disabled','disabled');
                        }
                        if (currentPlat.indexOf(2) < 0){
                            $("#shopInfo button[data-id='2']").attr('disabled','disabled');
                        }
                        self.doSearch();
                        self.initSidebar(shopId);
                        self.initActCategory(shopId);
                        self.initOnAct(shopId);
                        // var total = $(".pagination").attr("data-pages");
                        // self.initPagination(total);
                        // if (req.platforms.id == 10){
                        //     $("#shopInfo ul li:eq(0)").addClass("currentOutPlat");
                        // }
                    }else {
                        $("#shopInfo h3").html(req.message);
                        $("#shopInfo button").removeClass('active');
                        $("#shopInfo button").attr("disabled","disabled");
                        $("#tableContainer").html('');
                        $('#pagination').html('');
                        $('#goodsMenu').html('');
                    }
                },
                "error": function (req) {
                    CRM.showDialog("请求服务异常");
                }
            })
        },
        /*
        初始化活动类目
         */
        initActCategory: function (shopId) {
            CRM.request({
                "type": "GET",
                "url": CRM.getOuterUrl('/outway/sync/item/actcatInShop'),
                "dataType": "json",
                "data": {
                    "isp": $("#shopInfo button.active").attr('data-id'),
                    "shopId": shopId
                },
                "success": function (req) {
                    var html = "";
                    if (req.status){
                        if (req.entry != null){
                            for (var i = 0;i < req.entry.length;i++){
                                html += '<option value="' + req.entry[i].id + '">' + req.entry[i].name + '</option>'
                            }
                        }
                        html = '<option value="">选择活动类目</option>' + html;
                        $("#actCategories").html(html);
                        // $.each(req.entry,function (i,item) {
                        //     $("<option></option>")
                        //         .val(item["id"])
                        //         .text(item["name"])
                        //         .appendTo($("#actCategories"));
                        // });
                    } else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function (req) {
                    CRM.showDialog(req.message);
                }
            })
        },
        /*
        按填写参数搜索
         */
        doSearch: function (pageNo) {
            var pageNo = (pageNo == null) ? 1 : pageNo;
            var self = this;
            var currentShopId = $("#savedShopId").val();
            var currentCatId = "";
            if ($("#goodsMenu li.nowactive").length > 0){
                currentCatId = $("#goodsMenu li.nowactive").attr('data-value');
            }
            //console.log(currentCatId);
            if (currentShopId == ""){
                CRM.showDialog("请确认店铺ID正确");
            }else {
                CRM.request({
                    "type": 'GET',
                    "url": CRM.getOuterUrl("/outway/sync/item/page"),
                    "dataType": "json",
                    contentType: "application/json",
                    "data": {
                        "actcatId": $("#actCategories").val(),
                        "activityId": $("#onAct").val(),
                        "shopId": currentShopId,
                        "pageNo": pageNo,
                        //pageIndex,
                        "pageSize": pageSize,
                        "barcode": $("#goodsCode").val(),
                        "catId": currentCatId,
                        "isp": $("#shopInfo button.active").data('id'),
                        "itemId": $("#goodsId").val(),
                        "keyword": $("#goodsName").val(),
                        "status": $("#goodsStatus").val(),
                        "t": (new Date()).getTime()
                    },
                    "success": function (req) {
                        //刷新上下架按钮区
                        $("#putOnOrOff").css("display","block");
                        $("#failNotice").css("display","none");
                        //if (req.status && req.entry){
                        if (req.status){
                            //console.log('doSearch...');
                            self.renderList(req.entry.result,req.entry.totalCount,req.entry.pageNo);
                            $('.pagination').attr('data-pages',req.entry.totalCount);
                            var buttons = '<button type="button" class="btn btn-info" id="editPrices">批量修改价格</button>';
                            $("#editActGoodsPrice").html(buttons);
                        }else {
                            CRM.showDialog(req.message);
                        }
                    },
                    "error": function (req) {
                        CRM.showDialog("请求服务异常");
                    }
                });
            }
        },
        /*
        格式化价格
         */
        formatData: function (data) {
            for (var i = 0;i < data.length;i++){
                var li = data[i];
                li.price = (li.price/100).toFixed(2);
                li.outPrice = (li.outPrice/100).toFixed(2);
            }
            return data;
        },
        /*
        渲染表单
         */
        renderList: function (result,total,currentPage) {
            var self = this;
            var list = self.formatData(result);
            var html = outFlatListTpl({entry:list});
            var currentOutName = $("#shopInfo button.active").text() + "价格";
            //console.log('renderList...' + total + ',' + currentPage);
            var prevPages = $('.pagination').data('pages');
            $("#tableContainer").html(html);
            $("#outPriceChange").text(currentOutName);
            // if (FIRST_TIME_PAGI){
            self.initPagination(total,currentPage);
            //     FIRST_TIME_PAGI = false;
            // }
        },
        /*
        初始化分页器
         */
        initPagination: function (total,currentPage) {
            var self = this;
            var times = 1;
            var totalShow = '共 ' + total + ' 条';
            //console.log(currentPage);
            var total = (total == 0) ? 1 :total;
            //console.log(total);
            $('.pagination').html('<div id="pagination"></div>');
            $("#listTotalNum").text(totalShow);
            $('#pagination').twbsPagination({
                totalPages: Math.ceil(total/20) ,
                visiblePages: 7,
                startPage: currentPage,
                onPageClick: function (event, page) {
                    //console.log(event);
                    //console.log(page);
                    //self.pageNo = page;
                    if (times > 1){
                        self.doSearch(page);
                    }
                    times ++;
                }
            });
        },
        /*
        保存编辑价格
         */
        editOutPrice: function (id,price,targetInput,targetDiv,buttons) {
            var currentShopId = $("#savedShopId").val();
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/modifyPrice"),
                "dataType": "json",
                //contentType: "application/json",
                "data": {
                    "shopId": currentShopId,
                    "isp": $("#shopInfo button.active").data('id'),
                    "itemId": id,
                    "price": price,
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    if (req.status){
                        targetInput.attr('readonly','readonly');
                        targetDiv.attr('data-price',price);
                        targetDiv.html(buttons);
                        CRM.showDialog(req.message);
                    }else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /*
        重置为闪电购价格
         */
        resetPrice: function (id) {
            var self = this;
            var pageNo = parseInt($("#pagination li.active").text());
            var currentShopId = $("#savedShopId").val();
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl("/outway/sync/item/modifyPrice"),
                "dataType": "json",
                "contentType": "application/x-www-form-urlencoded",
                "data": {
                    "shopId": currentShopId,
                    "isp": $("#shopInfo button.active").data('id'),
                    "itemId": id
                },
                "success": function (req) {
                    if (req.status){
                        self.doSearch(pageNo);
                        CRM.showDialog(req.message);
                    }else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function () {
                    CRM.showDialog("请求服务异常");
                }
            });
        },
        /*
        保存编辑排序
         */
        editLevel: function (id,level,targetInput,targetDiv,buttons) {
            $.ajax({
                type: "POST",
                url: CRM.getOuterUrl("/outway/sync/item/modifyLevel"),
                dataType: "json",
                contentType: "application/x-www-form-urlencoded",
                data: {
                    "isp": $("#shopInfo button.active").attr('data-id'),
                    "itemId": id,
                    "level": level
                },
                xhrFields: {
                    withCredentials: true
                },
                success: function (req) {
                    if (req.status){
                        targetInput.attr('readonly','readonly');
                        targetDiv.attr('data-level',level);
                        targetDiv.html(buttons);
                        CRM.showDialog(req.message);
                    }else {
                        CRM.showDialog(req.message);
                        targetInput.removeAttr('readonly');
                        var btn = '<button type="button" class="btn btn-default btn-xs saveLevel" data-id="' + id + '" data-level="' + level + '">完成</button>' +
                            '<button type="button" class="btn btn-default btn-xs levelEditCancel" data-id="' + id + '">取消</button>';
                        targetDiv.html(btn);
                    }
                },
                error: function (req) {
                    CRM.showDialog(req.message);
                }
            })
        },
        /*
        上架商品
         */
        putOnItem: function (catId,itemIds) {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/online"),
                "dataType": "json",
                //contentType: "application/json",
                "data": {
                    "catId": catId,
                    "itemIds": itemIds,
                    "isp": $("#shopInfo button.active").data('id'),
                    "shopId": $("#savedShopId").val(),
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    if (req.status){
                        if (req.entry.length > 0){
                            $("#putOnOrOff").css("display","none");
                            $("#failNotice").css("display","block");
                            var html = onFailNoticeTpl({entry:req.entry});
                            $("#tableContainer").html(html);
                        }else {
                            CRM.showDialog(req.message);
                            self.doSearch();
                        }
                    }else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function (req) {
                    CRM.showDialog("请求服务异常");
                }
            });
        },
        /*
        下架商品
         */
        putOffItem: function (catId,itemIds) {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/offline"),
                "dataType": "json",
                //contentType: "application/json",
                "data": {
                    "catId": catId,
                    "itemIds": itemIds,
                    "isp": $("#shopInfo button.active").attr('data-id'),
                    "shopId": $("#savedShopId").val(),
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    if (req.status){
                        CRM.showDialog(req.message);
                        self.doSearch();
                    }else {
                        CRM.showDialog(req.message);
                    }

                }
            });
        },
        /*
        解绑商品
         */
        unBindCate: function (itemId) {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/unbanding/actcat"),
                "dataType": "json",
                //contentType: "application/json",
                "data": {
                    "isp": $("#shopInfo button.active").attr('data-id'),
                    "itemId": itemId
                },
                "success": function (req) {
                    if (req.status){
                        CRM.showDialog(req.message);
                        self.doSearch();
                    }else {
                        CRM.showDialog(req.message);
                    }

                },
                "error": function (req) {
                    CRM.showDialog("请求服务异常");
                }
            });
        },
        /*
        商品详情弹出
         */
        showDetailModal: function (itemId) {
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/detail"),
                "dataType": "json",
                "data": {
                    "isp": $("#shopInfo button.active").attr('data-id'),
                    "itemId": itemId,
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    //console.log(req.entry.outLevel);
                    if (req.status){
                        var ico = "";
                        if (req.entry.outCornerMarkId && req.entry.outCornerMarkUrl){
                            ico = '<img data-id="' + req.entry.outCornerMarkId + '" src="http://imgsize.52shangou.com/img/' + req.entry.outCornerMarkUrl + '">' + '<p><button type="button" class="btn btn-link btn-xs">删除</button></p>';
                        }
                        var outLevel = req.entry.outLevel > 0 ? req.entry.outLevel : "";
                        $("#edit_goodsBarcode").val(req.entry.barcode);
                        $("#edit_goodsCategory").val(req.entry.catName);
                        $("#edit_goodsImage img").attr('src','http://imgsize.52shangou.com/img/' + req.entry.bigPicUrl + '@80w');
                        $("#edit_goodsName").val(req.entry.itemName);
                        $("#edit_goodsID").val(req.entry.id);
                        $("#edit_goodsSpuId").val(req.entry.spuId);
                        $("#edit_goodsPrice").val((req.entry.price/100).toFixed(2));
                        $("#edit_outPrice").val((req.entry.outPrice/100).toFixed(2));
                        $("#edit_goodsStock").val(req.entry.quantity);
                        $("#edit_goodsIco").html(ico);
                        $("#edit_goodsBrand").val(req.entry.brand);
                        $("#edit_goodsSpec").val(req.entry.property);
                        $("#edit_goodsDesc").val(req.entry.description);
                        $("#edit_goodsPic").html(req.entry.richDescription);
                        $("#edit_goodsLevel").val(outLevel);
                        $("#edit_shopName").html($("#shopInfo h3").text());
                        $("#saveEdit").attr('data-itemId',itemId);
                        $("#select_goodsIco").attr('data-itemId',itemId);
                        $("#editGood_dialog").modal("show");
                    }else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function (req) {
                    CRM.showDialog("请求服务异常");
                }
            })
        },
        /*
        外店角标选择列表
         */
        showMarkList: function () {
            var self = this;
            self.markSearch();
            $("#marks_dialog").modal("show");
        },
        /*
        角标搜索
         */
        markSearch: function () {
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/itemcenter/crm/cornerMark/getCornerMarkByType.do"),
                "dataType": "json",
                "data": {
                    "city": $("#markOfCity").val(),
                    "name": $("#cornerMarkName").val(),
                    "type": $("#cornerMarkType").val(),
                    "t": (new Date()).getTime()
                },
                "success": function (req) {
                    var html = "";
                    if (req.status){
                        html = markListTpl({entry: req.entry});
                        $("#marks_dialog_content").html(html);
                    }else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function (req) {
                    CRM.showDialog("请求服务异常");
                }
            })
        },
        /*
        商品详情修改保存
         */
        saveDetail: function (itemId) {
            var self = this;
            var pageNo = parseInt($("#pagination li.active").text());
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl("/outway/sync/item/save"),
                "dataType": "json",
                "data": JSON.stringify({
                    "isp": $("#shopInfo button.active").attr('data-id'),
                    "itemId": itemId,
                    "cornerMarkId": $("#edit_goodsIco img").attr('data-id'),
                    "level": $("#edit_goodsLevel").val(),
                    "price": Math.round($("#edit_outPrice").val() * 100)
                }),
                "success": function (req) {
                    if (req.status){
                        CRM.showDialog(req.message);
                        self.doSearch(pageNo);
                    }else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function (req) {
                    CRM.showDialog("请求服务异常");
                }
            });
        },
        /*
        批量修改保存
         */
        saveChanges: function (dataList) {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl("/outway/sync/item/modifyPrice/batch"),
                "dataType": "json",
                "data": dataList,
                "success": function (req) {
                    if (req.status){
                        $("#wait_dialog").modal("hide");
                        CRM.showDialog(req.message);
                        var buttons = '<button type="button" class="btn btn-info" id="editPrices">批量修改价格</button>';
                        $("#editActGoodsPrice").html(buttons);
                        self.doSearch(pageNo);
                    }else {
                        $("#wait_dialog").modal("hide");
                        CRM.showDialog(req.message);
                    }
                },
                "error": function (req) {
                    CRM.showDialog("请求服务异常");
                }
            });
        },
        /*
        活动类目获取
         */
        initModalActCate: function () {
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/itemcenter/crm/frontCategory/actcat/list"),
                "dataType": "json",
                "data": {
                    "cityCode": $("#shopInfo h3").attr("data-city")
                },
                "success": function (req) {
                    var result = "";
                    if (req.status){
                        if (req.entry.length > 0){
                            for (var i = 0;i < req.entry.length;i++){
                                result += '<option value="' + req.entry[i].catIds[0] + '">' + req.entry[i].name + '</option>';
                            }
                            $("#relate_confirm_dialog_content select").html(result);
                        } else {
                            var noResult = '<option value="">该城市下没有相应的活动类目</option>'
                        }
                    }else {
                        $("#relate_confirm_dialog_content select").html("");
                        CRM.showDialog(req.message);
                    }

                },
                "error": function (req) {
                    CRM.showDialog("请求服务异常");
                }
            });
        },
        /*
        关联活动类目
         */
        relateAct: function (ids) {
            var self = this;
            var pageNo = parseInt($("#pagination li.active").text());
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl("/outway/sync/item/banding/actcat"),
                "dataType": "json",
                "contentType": "application/x-www-form-urlencoded",
                "data": {
                    "actcatId": $("#relate_confirm_dialog_content select").val(),
                    "isp": $("#shopInfo button.active").data('id'),
                    "itemIds": ids,
                    "shopId": $("#savedShopId").val()
                },
                "success": function (req) {
                    $("#relate_wait_dialog").modal("hide");
                    if (req.status){
                        self.doSearch(pageNo);
                        CRM.showDialog(req.message);
                    }else {
                        CRM.showDialog(req.message);
                    }
                },
                "error": function () {
                    CRM.showDialog("请求服务异常");
                }
            });
        },

        bindEvent: function () {
            var self = this;
            //内店id搜索
            $(document).delegate('#innerIdSearch','click',function () {
                var innerShopId = $("#innerShopId").val();
                //$("#savedShopId").val(innerShopId);
                // $("#shopInfo button").removeClass('active');
                // $("#shopInfo button").removeAttr('disabled');
                // $("#goodsStatus").val("");
                // $("#goodsId").val("");
                // $("#goodsCode").val("");
                // $("#goodsName").val("");
                //self.initSidebar(innerShopId);
                if (innerShopId == ""){
                    CRM.showDialog("内店ID不能为空");
                    // $("#tableContainer").html("");
                    // $("#pagination").html("");
                    // $("#putOnOrOff").css("display","block");
                    // $("#failNotice").css("display","none");
                    // $('#goodsMenu').html('');
                    // $("#shopInfo button").removeClass('active');
                    // $("#shopInfo button").attr("disabled","disabled");
                }else {
                    $("#shopInfo button").removeClass('active');
                    $("#shopInfo button").removeAttr('disabled');
                    $("#savedShopId").val(innerShopId);
                    $("#goodsStatus").val("");
                    $("#goodsId").val("");
                    $("#goodsCode").val("");
                    $("#goodsName").val("");
                    self.initShopInfo(innerShopId);
                }
                //self.doSearch();
            });
            //全选
            $(document).delegate('#selectAll','change',function () {
                self.selectAll(this.checked);
            });
            //编辑价格
            $(document).delegate('.changeOutPrice','click',function (e) {
                var target = $(e.currentTarget);
                var targetDiv = target.parent();
                var targetInput = targetDiv.siblings('input');
                targetInput.removeAttr('readonly');
                var targetPrice = targetInput.val();
                var id = target.attr('data-id');
                var buttons = '<button type="button" class="btn btn-default btn-xs savePrice" data-id="' + id + '">完成</button>' +
                    '<button type="button" class="btn btn-default btn-xs cancel" data-id="' + id + '">取消</button>';
                $("#editPrices").attr("disabled","disabled");//编辑价格未完成时禁止批量修改价格
                targetDiv.attr('data-price',targetPrice);
                targetDiv.html(buttons);
            });
            //保存价格编辑
            $(document).delegate('.savePrice','click',function (e) {
                var target = $(e.currentTarget);
                var targetDiv = target.parent();
                var id = target.attr('data-id');
                var buttons = '<button type="button" class="btn btn-default btn-xs changeOutPrice" data-id="' + id +'">编辑</button>'
                    + '<button type="button" class="btn btn-default btn-xs resetPrice" data-id="' + id + '" data-price="' + targetDiv.attr('data-resetprice') + '">重置</button>';
                var targetInput = targetDiv.siblings('input');
                //var decimalLength = targetInput.val().toString().split(".")[1].length;
                if (/^\d{1,4}(\.\d{1,2})?$/.test(targetInput.val())){
                    var targetPrice = Math.round(targetInput.val()*100);
                    self.editOutPrice(id,targetPrice,targetInput,targetDiv,buttons);
                    $("#editPrices").removeAttr("disabled");
                }else {
                    CRM.showDialog("请确认价格格式正确:位于0.01和9999.99间的两位小数数字");
                }
                //var targetPrice = Math.round(targetInput.val()*100);
                //targetInput.attr('readonly','readonly');
                //targetDiv.attr('data-price',targetPrice);
                //self.editOutPrice(id,targetPrice,targetInput,targetDiv,buttons);
                //targetDiv.html(buttons);
            });
            //取消价格编辑
            $(document).delegate('.cancel','click',function (e) {
                var target = $(e.currentTarget);
                var id = target.attr('data-id');
                var targetDiv = target.parent();
                var currentPriceVal = targetDiv.attr('data-price');
                var targetInput = targetDiv.siblings('input');
                targetInput.attr('readonly','readonly');
                targetInput.val(currentPriceVal);
                var buttons = '<button type="button" class="btn btn-default btn-xs changeOutPrice" data-id="' + id + '">编辑</button>'
                    + '<button type="button" class="btn btn-default btn-xs resetPrice" data-id="' + id + '" data-price="' + targetDiv.attr('data-resetprice') + '">重置</button>';
                targetDiv.html(buttons);
                $("#editPrices").removeAttr("disabled");
                targetInput.removeClass("typeError");
            });
            //编辑排序
            $("#tableContainer").on('click','.changeLevel',function (e) {
                //$("#tableContainer .outLevelBtn").html("");
                var target = $(e.currentTarget);
                var id = target.attr('data-id');
                var targetDiv = target.siblings('div');
                //var targetInput = targetDiv.siblings('input');
                var targetLevel = target.val();
                target.removeAttr('readonly');
                var buttons = '<button type="button" class="btn btn-default btn-xs saveLevel" data-id="' + id + '" data-level="' + targetLevel + '">完成</button>' +
                    '<button type="button" class="btn btn-default btn-xs levelEditCancel" data-id="' + id + '">取消</button>';
                targetDiv.attr('data-level',targetLevel);
                targetDiv.html(buttons);
            });
            //保存排序编辑
            $("#tableContainer").on('mousedown','.saveLevel',function (e) {
                e.preventDefault();//阻止失去焦点
                var target = $(e.currentTarget);
                var targetDiv = target.parent();
                var id = target.attr('data-id');
                var buttons = "";
                    //'<button type="button" class="btn btn-default btn-xs changeLevel" data-id="' + id +'">编辑</button>';
                var targetInput = targetDiv.siblings('input');
                if (/^[1-9]\d{0,3}$/.test(targetInput.val())){
                    var targetLevel = targetInput.val().trim();
                    self.editLevel(id,targetLevel,targetInput,targetDiv,buttons);
                } else if (targetInput.val().trim() == ""){//重置排序
                    if (confirm("是否重置排序")){
                        self.editLevel(id,"",targetInput,targetDiv,buttons);
                    }
                    // $("#reset_level_confirm").data('id',id);
                    // $("#reset_level_confirm").data('input',targetInput);
                    // $("#reset_level_confirm").data('div',targetDiv);
                    // $("#reset_level_confirm").data('btn',buttons);
                    // $("#reset_level_dialog").modal("show");
                }
                else {
                    CRM.showDialog("请确认排序数正确:位于1和9999间的整数");
                }
            });
            // $("#reset_level_confirm").on('click',function (e) {
            //     var target = $(e.currentTarget);
            //     var id = target.data('id');
            //     var inputEle = target.data('input');
            //     var level = "";
            //     var divEle = target.data('div');
            //     var btn = target.data('btn');
            //     self.editLevel(id,level,inputEle,divEle,btn);
            //     $("#reset_level_dialog").modal("hide");
            // });
            //取消排序编辑
            $("#tableContainer").on('mousedown','.levelEditCancel',function (e) {
                e.preventDefault();
                var target = $(e.currentTarget);
                var id = target.attr('data-id');
                var targetDiv = target.parent();
                var currentLevelVal = targetDiv.attr('data-level');
                var targetInput = targetDiv.siblings('input');
                targetInput.attr('readonly','readonly');
                targetInput.val(currentLevelVal);
                var buttons = "";
                    //'<button type="button" class="btn btn-default btn-xs changeLevel" data-id="' + id + '">编辑</button>';
                targetDiv.html(buttons);
            });
            //失去光标隐藏按钮
            $("#tableContainer").on('blur','.changeLevel',function (e) {
                var target = $(e.currentTarget);
                var id = target.attr('data-id');
                var targetDiv = target.siblings('div');
                var currentLevelVal = targetDiv.attr('data-level');
                if (currentLevelVal == "null"){
                    currentLevelVal = "";
                }
                // var savedValue = target.val();
                // if (savedValue != currentLevelVal){
                //     currentLevelVal = savedValue;
                // }
                //var targetInput = targetDiv.siblings('input');
                target.attr('readonly','readonly');
                target.val(currentLevelVal);
                var buttons = "";
                targetDiv.html(buttons);
            });
            //点击外店按钮搜索
            $("#shopInfo").delegate('button','click',function (e) {
                //e.stopPropagation();
                var target = $(e.currentTarget);
                $("#shopInfo button").removeClass('active');
                target.addClass('active');
                //console.log(target);
                self.doSearch();
                // var total = $(".pagination").attr("data-pages");
                // self.initPagination(total);
            });
            //参数搜索
            $(document).delegate('#search_goods','click',function () {
                var hasOutShop = $("#shopInfo button.active").data('id');
                if (hasOutShop){
                    self.doSearch();
                }else {
                    CRM.showDialog("请确认店铺ID正确")
                }
                // var total = $(".pagination").attr("data-pages");
                // self.initPagination(total);
            });
            //点击类目搜索商品
            $('#goodsMenu').delegate('a','click',function (e) {
                e.preventDefault();
                //e.stopPropagation();//阻止事件冒泡,防止点子级父级获得焦点
                var target = $(e.currentTarget);
                var targetLi = target.parent();
                $("#goodsMenu li").removeClass('nowactive');
                targetLi.addClass('nowactive');
                self.doSearch();
                // var total = $(".pagination").attr("data-pages");
                // self.initPagination(total);
            });
            //点击"类目修改商品"按钮弹出层
            $(document).delegate('#changeByType','click',function () {
                var typeList = [];
                var typeIds = [];
                var html = "";
                $("#goodsMenu li li>a").each(function () {
                    typeList.push($(this).text());
                    typeIds.push($(this).parent().attr('data-value'));
                });
                var buttons = '</label><button type="button" class="col-xs-3 btn btn-default putOnByType">' +
                        '商品上架</button><button type="button" class="col-xs-3 btn btn-default putOffByType">商品下架</button></div>';
                for (var i = 0;i < typeList.length;i++){
                    html += '<div class="form-group col-xs-12"><label class="control-label col-xs-6" data-id="' +typeIds[i] + '">' + typeList[i] + buttons;
                }
                var _html = '<div class="panel panel-default"><div class="panel-body"><form class="navbar-form navbar-left" role="form">' + html +'</form></div></div>';
                $("#typePut_dialog_content").html(_html);
                $("#typePut_dialog").modal("show");
            });
            //按类目上架商品
            $(document).delegate('.putOnByType','click',function (e) {
                var target = $(e.currentTarget);
                var targetCatID = target.siblings('label').attr('data-id');
                $("#typePut_dialog").modal("hide");
                $("#targetCatID").val(targetCatID);
                $("#targetItemIDs").val("");
                $("#confirm_dialog_title").text("是否全部上架该类目商品?");
                $("#confirm").attr('data-putType','puton');
                $("#confirm_dialog").modal('show');
            });
            //上架失败返回
            $("#failNotice").delegate('button','click',function () {
                $("#putOnOrOff").css("display","block");
                $("#failNotice").css("display","none");
                self.doSearch();
                // var total = $(".pagination").attr("data-pages");
                // self.initPagination(total);
            });
            //按类目下架商品
            $(document).delegate('.putOffByType','click',function (e) {
                var target = $(e.currentTarget);
                //console.log(target);
                var targetCatID = target.siblings('label').attr('data-id');
                $("#typePut_dialog").modal("hide");
                $("#targetCatID").val(targetCatID);
                $("#targetItemIDs").val("");
                $("#confirm_dialog_title").text("是否全部下架该类目商品?");
                $("#confirm").attr("data-putType","putoff");
                $("#confirm_dialog").modal('show');
            });
            //弹出框确认上下架
            $(document).delegate('#confirm','click',function () {
                var catId = $("#targetCatID").val();
                var itemIds = $("#targetItemIDs").val();
                var putType = $("#confirm").attr('data-putType');
                if (putType == 'puton'){
                    self.putOnItem(catId,itemIds);
                } else if (putType == 'putoff'){
                    self.putOffItem(catId,itemIds);
                }
                $("#confirm_dialog").modal('hide');
            });
            //多选||单选上架
            $(document).delegate('#putOn','click',function () {
                var arr = [];
                $("#tableContainer tr").each(function () {
                    var itemId = $(this).find('input.onlySelect').val();
                    var checkbox = $(this).find('input.onlySelect');
                    if (itemId && checkbox.prop('checked')){
                        arr.push(itemId);
                    }
                });
                var catId = "";
                var itemIds = arr.toString(',');
                if (itemIds == ""){
                    CRM.showDialog("没有选中商品");
                }else {
                    $("#targetCatID").val("");
                    $("#targetItemIDs").val(itemIds);
                    $("#confirm_dialog_title").text("是否上架选中商品?");
                    $("#confirm").attr('data-putType','puton');
                    $("#confirm_dialog").modal('show');
                }
                //self.putOnItem(catId,itemIds);
            });
            //多选||单选下架
            $(document).delegate('#putOff','click',function () {
                var arr = [];
                $("#tableContainer tr").each(function () {
                    var itemId = $(this).find('input.onlySelect').val();
                    var checkbox = $(this).find('input.onlySelect');
                    if (itemId && checkbox.prop('checked')){
                        arr.push(itemId);
                    }
                });
                var catId = "";
                var itemIds = arr.toString(',');
                if (itemIds == ""){
                    CRM.showDialog("没有选中商品");
                }else {
                    $("#targetCatID").val("");
                    $("#targetItemIDs").val(itemIds);
                    $("#confirm_dialog_title").text("是否下架选中商品?");
                    $("#confirm").attr('data-putType','putoff');
                    $("#confirm_dialog").modal('show');
                }
                //self.putOffItem(catId,itemIds);
            });
            //列表中选择上架
            $(document).delegate('.listPutOn','click',function (e) {
                var target = $(e.currentTarget);
                var itemId = target.attr('data-id');
                var catId = "";
                $("#targetCatID").val("");
                $("#targetItemIDs").val(itemId);
                $("#confirm_dialog_title").text("是否上架商品?");
                $("#confirm").attr('data-putType','puton');
                $("#confirm_dialog").modal('show');
                //self.putOnItem(catId,itemId);
            });
            //列表中选择下架
            $(document).delegate('.listPutOff','click',function (e) {
                var target = $(e.currentTarget);
                var itemId = target.attr('data-id');
                var catId = "";
                $("#targetCatID").val("");
                $("#targetItemIDs").val(itemId);
                $("#confirm_dialog_title").text("是否下架商品?");
                $("#confirm").attr('data-putType','putoff');
                $("#confirm_dialog").modal('show');
                //self.putOffItem(catId,itemId);
            });
            //列表中选择解绑操作
            $(document).delegate('.listUnBind','click',function (e) {
                var target = $(e.currentTarget);
                var itemId = target.attr('data-id');
                $("#unbind_confirm").attr('data-id',itemId);
                var str = '商品ID: ' + itemId;
                $("#unbind_confirm_dialog_content p").text(str);
                $("#unbind_confirm_dialog").modal("show");
                //self.unBindCate(itemId);
            });
            //确认解绑
            $("#unbind_confirm").on('click',function (e) {
                var target = $(e.currentTarget);
                var targetId = target.attr('data-id');
                self.unBindCate(targetId);
                $("#unbind_confirm_dialog").modal("hide");
            })
            //列表中选择编辑商品
            $("#tableContainer").on('click','.listEditGood',function (e) {
                var target = $(e.currentTarget);
                var itemId = target.attr('data-id');
                $("#edit_goodsIco").html('');
                self.showDetailModal(itemId);
            });
            //角标列表
            $("#select_goodsIco").on('click',function (e) {
                var target = $(e.currentTarget);
                var itemId = target.attr('data-itemId');
                $("#returnToModal").attr('data-itemId',itemId);
                self.showMarkList();
            });
            //搜索角标
            $("#searchCornerMark").on('click',function () {
                self.markSearch();
            });
            //选择角标
            $("#marks_dialog_content").on('click','img',function (e) {
                var target =$(e.currentTarget);
                var targetId = target.attr('data-id');
                var targetUrl = target.attr('src');
                $("#marks_dialog").modal("hide");
                var html = '<img data-id="' + targetId + '" src="' + targetUrl + '">' + '<p><button type="button" class="btn btn-link btn-xs">删除</button></p>';
                $("#edit_goodsIco").html(html);
            });
            //删除角标
            $("#edit_goodsIco").on('click','button',function (e) {
                var markStr = "";
                $("#edit_goodsIco").html(markStr);
            });
            //保存商品信息修改
            $("#saveEdit").on('click',function (e) {
                var target = $(e.currentTarget);
                var itemId = target.attr('data-itemId');
                if ((/^[1-9]\d{0,3}$/.test($("#edit_goodsLevel").val()) && /^\d{1,4}(\.\d{1,2})?$/.test($("#edit_outPrice").val())) || $("#edit_goodsLevel").val().trim() == ""){
                    self.saveDetail(itemId);
                }else if (!/^[1-9]\d{0,3}$/.test($("#edit_goodsLevel").val())) {
                    CRM.showDialog('排序数的范围为1到9999');
                } else if (!/^\d{1,4}(\.\d{1,2})?$/.test($("#edit_outPrice").val())) {
                    CRM.showDialog("请确认价格格式正确:位于0.01和9999.99间的两位小数数字");
                }
            });
            //批量修改价格
            $("#editActGoodsPrice").on('click',"#editPrices",function () {
                $(".changeOutPrice").css('display','none');
                $(".resetPrice").css('display','none');
                $(".editOutPrice").removeAttr('readonly');
                var buttons = '<button type="button" class="btn btn-success" id="savePrices">保存批量修改</button>' +
                    '<button type="button" class="btn btn-warning" id="unSavePrices">取消批量修改</button>';
                $("#editActGoodsPrice").html(buttons);
            });
            //批量修改价格验证
            $("#tableContainer").on('blur','.editOutPrice',function (e) {
                var target = $(e.currentTarget);
                console.log(target);
                var price = target.val();
                if (/^\d{1,4}(\.\d{1,2})?$/.test(price)){
                    target.removeClass('typeError');
                }else {
                    target.addClass('typeError');
                }
            });
            //保存批量修改弹出确认
            $("#editActGoodsPrice").on('click','#savePrices',function () {
                // var dataList = [];
                // $.each($(".editOutPrice"),function (i,item) {
                //     var temp = {};
                //     temp["itemId"] = $(item).attr('data-id');
                //     temp["price"] = $(item).val();
                //     temp["isp"] = $("#shopInfo button.active").attr('data-id');
                //     dataList.push(temp);
                // });
                //console.log(dataList);
                //$("#changes_confirm").attr('data-send',dataList);
                if ($(".editOutPrice").hasClass('typeError')){
                    CRM.showDialog('请确认价格格式正确:位于0.01和9999.99间的两位小数数字');
                }else {
                    $("#changes_confirm_dialog").modal('show');
                }
            });
            //确认保存批量修改
            $("#changes_confirm").on('click',function (e) {
                var pageNo = parseInt($("#pagination li.active").text());
                var target = $(e.currentTarget);
                // var dataList = target.attr('data-send');
                // console.log(dataList);
                var dataList = [];
                $.each($(".editOutPrice"),function (i,item) {
                    var temp = {};
                    temp["itemId"] = $(item).attr('data-id');
                    temp["price"] = Math.round($(item).val() * 100);
                    temp["isp"] = $("#shopInfo button.active").attr('data-id');
                    dataList.push(temp);
                });
                self.saveChanges(JSON.stringify(dataList));
                $("#changes_confirm_dialog").modal("hide");
                $("#wait_dialog").modal("show");
                // var buttons = '<button type="button" class="btn btn-default" id="editPrices">批量修改商品价格</button>';
                // $("#editActGoodsPrice").html(buttons);
                // self.doSearch(pageNo);
            });
            //取消批量修改
            $("#editActGoodsPrice").on('click','#unSavePrices',function () {
                var pageNo = parseInt($("#pagination li.active").text());
                var buttons = '<button type="button" class="btn btn-info" id="editPrices">批量修改价格</button>';
                $("#editActGoodsPrice").html(buttons);
                self.doSearch(pageNo);
            });
            //回车搜索
            $(document).on('keydown',function (e) {
                //e.preventDefault();
                var innerShopId = $("#innerShopId").val();
                if (e.keyCode == 13 && $("#innerShopId").is(":focus")){
                    e.preventDefault();
                    if (innerShopId == ""){
                        CRM.showDialog("内店ID不能为空");
                    }else {
                        $("#shopInfo button").removeClass('active');
                        $("#shopInfo button").removeAttr('disabled');
                        $("#savedShopId").val(innerShopId);
                        $("#goodsStatus").val("");
                        $("#goodsId").val("");
                        $("#goodsCode").val("");
                        $("#goodsName").val("");
                        self.initShopInfo(innerShopId);
                    }
                }
            });
            //重置为闪电购价格
            $("#tableContainer").on('click','.resetPrice',function (e) {
                var target = $(e.currentTarget);
                var targetId = target.attr('data-id');
                var targetPrice = target.attr('data-price');
                $("#reset_confirm_dialog_content span").text(targetPrice);
                $("#reset_confirm").attr('data-id',targetId);
                $("#reset_confirm_dialog").modal("show");
                //self.resetPrice(targetId);
            });
            //确认重置
            $("#reset_confirm").on('click',function (e) {
                var target = $(e.currentTarget);
                var targetId = target.attr('data-id');
                self.resetPrice(targetId);
                $("#reset_confirm_dialog").modal("hide");
            });
            //多选||单选关联活动类目弹出层
            $("#relateGoods").on('click',function () {
                var arr = [];
                $("#tableContainer tr").each(function () {
                    var itemId = $(this).find('input.onlySelect').val();
                    var checkbox = $(this).find('input.onlySelect');
                    if (itemId && checkbox.prop('checked')){
                        arr.push(itemId);
                    }
                });
                var itemIds = arr.toString(',');
                if (itemIds == ""){
                    CRM.showDialog("没有选中商品");
                }else {
                    $("#relate_confirm").attr('data-ids',itemIds);
                    self.initModalActCate();
                    $("#relate_confirm_dialog").modal('show');
                }
            });
            //选择关联类目
            $("#relate_confirm").on('click',function (e) {
                var target = $(e.currentTarget);
                var targetIds = target.attr('data-ids');
                self.relateAct(targetIds);
                $("#relate_confirm_dialog").modal("hide");
                $("#relate_wait_dialog").modal("show");
            });
        }
    };

    outflat.init();


});